package com.dapeis.service;

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.ag.dao.DBService;
import com.ag.dao.IDao;
import com.ag.utils.DictionarySettingUtils;
import com.ag.utils.NumberUtils;
import com.dapeis.core.utils.StringUtil;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.dao.ICouponsMapper;
import com.dapeis.domain.Coupons;
import com.dapeis.domain.Order;
import com.dapeis.domain.User;
import com.dapeis.exception.CounponsCodeExtisException;

@Service
public class CouponsService extends DBService<Coupons> {

    @Resource
    UserService userServer;

    @Resource
    ICouponsMapper mapper;

    @Override
    protected IDao<Coupons> getIDao() {
	return mapper;
    }

    /**
     * 订单完成服务时调用
     * 
     * @param order
     * @param userId
     * @return
     */
    public boolean doOrderFinishCoupons(Order order, Integer userId) {
	if (NumberUtils.isValid(order.getCouponsId())) {
	    Coupons coupons = mapper.selectByPrimaryKey(order.getCouponsId());
	    // 该订单使用过优惠券且是兑换的优惠券,才给用户增加券
	    if (null != coupons
		    && coupons.getType().equals(
			    StylistConstants.Coupons.Type.EXCHANGE)) {
		createCoupons(coupons.getSourceUserId(), userId,
			StylistConstants.Coupons.Type.PROMOTION);
	    }
	}
	return createCouponsCode(userId);
    }

    /**
     * 生成优惠吗 完成服务
     * 
     * @param userId
     * @return
     */
    public boolean createCouponsCode(Integer userId) {
	User user = userServer.selectByPrimaryKey(userId);
	if (StringUtil.isNotBlank(user.getCouponsCode())) {
	    return true;
	}

	String tempCode = StylistConstants.getCouponsCode();
	while (null != getUserByCouponsCode(tempCode)) {
	    // 当优惠码能查到用户时
	    tempCode = StylistConstants.getCouponsCode();
	}
	user.setCouponsCode(tempCode);
	return userServer.updateByPrimaryKeySelective(user) > 0;
    }

    /**
     * 根据优惠吗查找用户
     * 
     * @param tempCode
     * @return
     */
    public User getUserByCouponsCode(String tempCode) {
	Example example = new Example(User.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(User.PROPERTY_COUPONSCODE, tempCode);
	return userServer.selectOneByExample(example);

    }

    /**
     * 兑换
     * 
     * @param couponsCode
     * @param userId
     * @return
     */
    public Coupons exchange(String couponsCode, Integer userId) {
	User user = getUserByCouponsCode(couponsCode);
	if (null == user) {
	    // 无效的兑换码
	    throw new CounponsCodeExtisException();
	}
	if (userId == user.getId()) {
	    throw new CounponsCodeExtisException("该优惠码是您自己的,不能兑换哦！");
	}
	if (isExchange(userId)) {
	    throw new CounponsCodeExtisException("该活动只能兑换一次!");
	}
	return createCoupons(userId, user.getId(),
		StylistConstants.Coupons.Type.EXCHANGE);
    }

    /**
     * 创建优惠券
     * 
     * @param userId
     * @param sourceId
     * @param type
     * @return
     */
    public Coupons createCoupons(Integer userId, Integer sourceId, String type) {
	Coupons coupons = new Coupons();
	Integer price = new Integer(DictionarySettingUtils.getParameterValue(
		"cfg.coupons.cons.price").toString());
	coupons.initCoupons("咨询优惠券", price, userId, sourceId, type);
	if (mapper.insertSelective(coupons) > 0) {
	    return coupons;
	}
	throw new CounponsCodeExtisException("生成优惠券异常");
    }

    /**
     * 检查该用户是否兑换过(是否参与过该活动) true 兑换过 false 没兑换过
     * 
     * @param userId
     * @return
     */
    public boolean isExchange(Integer userId) {
	Example example = new Example(Coupons.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(Coupons.PROPERTY_USERID, userId);
	criteria.andEqualTo(Coupons.PROPERTY_TYPE,
		StylistConstants.Coupons.Type.EXCHANGE);
	return mapper.selectCountByExample(example) > 0;
    }

    /**
     * 用户我的优惠券
     * 
     * @param userId
     * @return
     */
    public List<Coupons> getMyCoupons(Integer userId) {
	updateCouponsStatus(userId);
	Example example = new Example(Coupons.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(Coupons.PROPERTY_USERID, userId);
	return mapper.selectByExample(example);
    }

    /**
     * 获取我的优惠券(可用的)
     * 
     * @param userId
     * @return
     */
    public List<Coupons> getMyCouponsNormal(Integer userId) {
	updateCouponsStatus(userId);
	Example example = new Example(Coupons.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(Coupons.PROPERTY_USERID, userId);
	criteria.andEqualTo(Coupons.PROPERTY_STATU,
		StylistConstants.Coupons.status.NORMAL);
	return mapper.selectByExample(example);
    }

    /**
     * 更新用户优惠券状态
     * 
     * @param userId
     */
    public void updateCouponsStatus(Integer userId) {
	Example example = new Example(Coupons.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(Coupons.PROPERTY_USERID, userId);
	criteria.andEqualTo(Coupons.PROPERTY_STATU,
		StylistConstants.Coupons.status.NORMAL);
	List<Coupons> list = mapper.selectByExample(example);
	if (null != list && !list.isEmpty()) {
	    for (Iterator iterator = list.iterator(); iterator.hasNext();) {
		Coupons coupons = (Coupons) iterator.next();
		if (coupons.getExpiryDate() <= new Date().getTime() / 1000) {
		    coupons.setStatus(StylistConstants.Coupons.status.EXPIRATION);
		    updateByPrimaryKeySelective(coupons);
		}
	    }
	}
    }
}
